package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autocofig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.Exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MovementsService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    /*
     * 发布动态
     * */
    public void pulishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        //判断动态的内容是否存在
        if (StringUtils.isEmpty(movement.getTextContent())) {
            throw new BusinessException(ErrorResult.contentError());
        }
        //获取用户id
        Long userId = UserHolder.getUserId();
        //将文件上传如阿里云OSS
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(upload);
        }
        //将数据封装到Movement对象
        movement.setUserId(userId);
        movement.setMedias(medias);
        //调用API完成发布动态
        movementApi.publish(movement);
    }

    /*
     * 查询个人动态
     * */
    public PageResult findByUserId(Long userId, Integer page, Integer pageSize) {
        //根据用户id，调用API查询个人动态内容
        PageResult pr = movementApi.findByUserId(userId, page, pageSize);
        //获取PageResult中的item对象
        List<Movement> items = (List<Movement>) pr.getItems();
        //非空判断
        if (items == null) {
            return pr;
        }
        //循环数据列表
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> list = new ArrayList<>();
        for (Movement item : items) {
            //一个Movement构建一个Vo对象
            MovementsVo vo = MovementsVo.init(userInfo, item);
            list.add(vo);
        }
        //构建返回值
        pr.setItems(list);
        return pr;
    }

    //查询好友动态
    public PageResult findFriendMovements(Integer page, Integer pagesize) {
        //获取当前用户Id
        Long userId = UserHolder.getUserId();
        //调用api查询当前用户好友发布的动态列表
        List<Movement> list = movementApi.findFriendMovements(page, pagesize, userId);
        return getPageResult(page, pagesize, list);
    }


    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> list) {
        //判断列表是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取发布人的id列表
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //获取用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //一个Movement构造一个Vo对象
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : list) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                //修复点赞状态的BUG
                String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                ;
                //修复喜欢状态的BUG
                String LoveHashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, LoveHashKey)) {
                    vo.setHasLoved(1);
                }
                ;
                vos.add(vo);
            }
        }
        //构造返回值并返回
        return new PageResult(page, pagesize, 0L, vos);
    }

    /*
     * 查询推荐动态
     * */
    public PageResult findRecommendMovements(Integer page, Integer pagesize) {
        //从redis中获取推荐数据
        String redisKey = Constants.MOVEMENTS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //判断推荐数据是否存在
        List<Movement> list = Collections.EMPTY_LIST;
        if (StringUtils.isEmpty(redisValue)) {
            //调用API随机构造10条动态数据
            list = movementApi.randomMovement(pagesize);
        } else {
            //处理pid数据
            String[] values = redisValue.split(",");
            //判断当前页的七十条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> pids = Arrays.stream(values)
                        .skip((page - 1) * pagesize)
                        .limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //根据PID数组查询动态数据
                list = movementApi.findMovementsByPids(pids);
            }
        }
        //调用公共方法构造返回值
        return getPageResult(page, pagesize, list);
    }

    /*
     * 根据id查询动态
     * */
    public MovementsVo findById(String movementId) {
        //调用api根据id查询动态详情
        Movement movement = movementApi.findById(movementId);
        if (movement != null) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            return MovementsVo.init(userInfo, movement);
        } else {
            return null;
        }
    }

    /*
     * 首页-访客列表
     * */
    public List<VisitorsVo> queryVisitorsList() {
        //查询访问时间
        String key = Constants.VISITORS_USER;
        String hashKey = UserHolder.getUserId().toString();
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        Long date = StringUtils.isEmpty(value)?null:Long.valueOf(value);
        //调用api查询数据列表
        List<Visitors> list = visitorsApi.queryMyVisitors(date,UserHolder.getUserId());
        if (CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        //提取用户ID
        List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //查看用户详情
        List<VisitorsVo> vos = new ArrayList<>();
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        for (Visitors visitors : list) {
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            if (userInfo!=null){
                VisitorsVo vo = VisitorsVo.init(userInfo, visitors);
                vos.add(vo);
            }
        }
        //构造返回
        return vos;
    }
}
